extends PanelContainer

@export var subtaskEn:SubtaskEntity 

#获得需要更新或者显示的组件
@onready var seq_no_label = %no_label
@onready var subtask_name_le = %subtaskLE
@onready var working_hours = $HBoxContainer/gridcontainer/HBoxContainer/PanelContainer/SpinBox
@onready var milestoneCB = $HBoxContainer/gridcontainer/milestoneCheck

@onready var related_file_container = %related_file_container
@onready var related_file_comp_scene = preload("res://components/relatedfile_comp.tscn")

# Called when the node enters the scene tree for the first time.
func _ready():
	_set_subtask(subtaskEn)
	Signalbus.related_file_deled.connect(_on_related_file_deled)


func _set_subtask(subtaskEN:SubtaskEntity):
	seq_no_label.text = str(subtaskEN.subtask_seq_no)
	subtask_name_le.text = subtaskEN.name
	working_hours.value = subtaskEN.subtask_hours
	milestoneCB.button_pressed = subtaskEN.isMileStone
	
	for filepath in subtaskEN.related_files:
		_add_related_file_ui(filepath)

func _get_subtask_entity():
	subtaskEn.subtask_seq_no = int(seq_no_label.text)
	subtaskEn.name = subtask_name_le.text
	subtaskEn.subtask_hours = working_hours.value
	subtaskEn.isMileStone = milestoneCB.button_pressed
	return subtaskEn

func _on_del_pressed():
	Signalbus.subtask_deled.emit(subtaskEn.belonged_task_id,_get_subtask_entity())
	self.queue_free()

# 选择linkfile
func _on_link_file_btn_pressed():
	%selectFileDialog.show()

func _on_select_file_dialog_file_selected(path):
	_add_related_file(path)

# 添加链接路径的方法
func _add_related_file(filepath:String):
	# 先保存到数据
	subtaskEn.related_files.append(filepath)
	_add_related_file_ui(filepath)

func _add_related_file_ui(filepath:String):
	# 更新UI
	var relatedFileComp = related_file_comp_scene.instantiate()
	relatedFileComp.filepath = filepath
	related_file_container.add_child(relatedFileComp)

func _on_related_file_deled(path):
	subtaskEn.related_files.erase(path)
